package org.ucas.faker.web.service.Visualization;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.faker.web.fetcher.FetchExecutor;
import org.ucas.faker.web.fetcher.FetchReqBuilder;
import org.ucas.faker.web.fetcher.FetchResult;
import org.ucas.faker.web.service.Visualization.entity.VisualParam;
import org.ucas.faker.web.service.Visualization.json.DBUtil;
import org.ucas.faker.web.service.Visualization.json.JsonUtil;

import java.util.List;

@Service
@Transactional
public class LabelService extends DataService {
    @Autowired
    private FetchExecutor fetcher;

    public void getBasisLabel(JSONObject inputJson, FetchReqBuilder requestBuilder, VisualParam param) {
        String basisKey = JsonUtil.getValue(inputJson, "basis.key");
        parseBasisLabelAndRangeAndOrder(inputJson, requestBuilder, param);

        requestBuilder.select(basisKey).count("*", DBUtil.keyCount(basisKey)).group(basisKey).not_null(basisKey);
        System.out.println("SQL: " + requestBuilder.build());
        FetchResult result = fetcher.fetch(requestBuilder.build());

        List countList = result.column(DBUtil.keyCount(basisKey));
        List keyList = result.column(basisKey);

        for (int i = 0; i < keyList.size(); i++) {
            System.out.println(keyList.get(i) + "\t" + countList.get(i));
        }

        param.setBasisLabel(JsonUtil.listToJsonArray(keyList));
        param.setDataList(countList);
        combineBasisHyperset(inputJson, param);
        System.out.println("SQL " + requestBuilder.build().sql());
    }
}
